<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>销售订单记录</title>
    <script type="text/javascript">
      var newSaleOrderWin;
      var editSaleOrderWin;
      var editSaleOrderAfterAuditWin
      var saleOrderId;
      var deliveryForSaleWin;
      var saleIntoPurchaseWin;
      var newSaleReturnedWin;
      var newSaleExchangeWin;
      var recListWin;
      var saleOrderDS;
      Ext.onReady(function(){
        
        var customerTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        customerTemplate.compile();
        var customerStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/customer/getAllCustomers?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number',
              convert:function(value,record){
                if (value === ""){
                  return "未设置编号"
                }else{
                  return value;
                }
              }
            }, {
              name: 'name'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'address'
            }])
        });

        var customer =  new Ext.form.ComboBox({
          fieldLabel: '客户',
          store: customerStore,
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'customer_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          pageSize: 10,
          //hideTrigger: false,
          tpl: customerTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true,
          triggerAction:"all",
          anchor: '100%'
        });
               
        var orderNumber = new Ext.form.TextField({
          fieldLabel: '单号',
          name: 'order_number',
          anchor: '100%'
        });
        
        var stateStore = new Ext.data.ArrayStore({
          fields: ['text','value'],
          data : auditStatusArray
        });
        
        var auditingStatus = new Ext.form.ComboBox({
          fieldLabel: '审批状态',
          store: stateStore,
          displayField:'text',
          typeAhead: true,
          mode: 'local',
          name: 'auditing_status',
          forceSelection: true,
          triggerAction: 'all',
          editable:false,
          valueField: 'value',
          emptyText:'',
          selectOnFocus:true,
          anchor: '100%'
        })

        var beginDate = new Ext.form.DateField({
          fieldLabel: '发货日期',
          name: 'begin_date',
          id: 'begin_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          vtype: 'daterange',
          endDateField: 'end_date',
          listeners: {
            select: function(field, e){
              //Ext.MessageBox.alert('提示', '提交成功');
            }
          },
          anchor: '100%'
        });
        
        var endDate = new Ext.form.DateField({
          fieldLabel: '至',
          name: 'end_date',
          id: 'end_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          vtype: 'daterange',
          startDateField: 'begin_date',
          listeners: {
            select: function(field, e){
              //Ext.MessageBox.alert('提示', '提交成功');
            }
          },
          anchor: '100%'
        });

        var productTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">','<div style="float:left; width:220px">{name}</div><div style="float:left; width:90px">{number}</div>{is_suit}','</div></tpl>');
        productTemplate.compile();
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product/getAllProducts?for_cbb=true_simple"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          fieldLabel: '产品',
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'product_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          //hideTrigger: false,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:"all",
          selectOnFocus:true
        });

        var employeeTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div>{name}</div>', '</div></tpl>');
        employeeTemplate.compile();
        var employeeStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/employee/getAllEmployees?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });
        
        //销售员
        var employeeCBB = new Ext.form.ComboBox({
          store: employeeStore,
          fieldLabel: '销售员',
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'employee_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: employeeTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:"all",
          selectOnFocus:true
        });

        //部门
        var departmentTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div>{name}</div>', '</div></tpl>');
        departmentTemplate.compile();
        var departmentStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/department/getAllDepartments?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'department_id',
              mapping: 'id'
            }, {
              name: 'number'
            }, {
              name: 'name'
            }])
        });
        departmentStore.load();
        //供应商
        var department = new Ext.form.ComboBox({
          store: departmentStore,
          fieldLabel: '业绩部门',
          allowBlank: false,
          blankText: "部门必须选择",
          valueField: 'department_id',
          displayField: 'name',
          hiddenName: 'sell_dept_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          //pageSize: 10,
          //hideTrigger: false,
          readOnly:false,
          tpl: departmentTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:"all",
          selectOnFocus:true
        });

        var cBeginDate = new Ext.form.DateField({
          fieldLabel: '制单日期',
          name: 'c_begin_date',
          id: 'c_begin_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          anchor: '100%',
          vtype: 'daterange',
          endDateField: 'c_end_date'
        });

        var cEndDate = new Ext.form.DateField({
          fieldLabel: '至',
          name: 'c_end_date',
          id: 'c_end_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",
          inputType: '2010-01-01',
          anchor: '100%',
          vtype: 'daterange',
          startDateField: 'c_begin_date'
        });
        
        var searchButton = new Ext.Button({
          text: '搜索',
          iconCls: 'finding',
          width:70,
          handler: function(){
            saleOrderDS.removeAll();
            saleOrderDS.baseParams.order_number = orderNumber.getValue();
            saleOrderDS.baseParams.auditing_status = auditingStatus.getValue();
            saleOrderDS.baseParams.sales_id = employeeCBB.getValue();
            saleOrderDS.baseParams.product_id = productCBB.getValue();
            saleOrderDS.baseParams.begin_date = beginDate.getRawValue();
            saleOrderDS.baseParams.end_date = endDate.getRawValue();
            saleOrderDS.baseParams.customer_id = customer.getValue();
            saleOrderDS.baseParams.sell_dept_id = department.getValue();
            saleOrderDS.baseParams.c_begin_date = cBeginDate.getRawValue();
            saleOrderDS.baseParams.c_end_date = cEndDate.getRawValue();
            saleOrderDS.load();
          }
        });

        var clearButton = new Ext.Button({
          text: '清空',
          width:50,
          handler: function(){
            queryFormPanel.form.reset();
          }
        });

        var queryFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'query_form',
          labelWidth: 60,
          width: screenWidth-175,
          labelAlign: 'right',
          frame : true,
          border:false,
          items: [{
              xtype: 'fieldset',
              defaults: {width: screenWidth-190},
              title: '查询条件',
              border: true,
              items: [{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .12,
                      layout: 'form',
                      border: false,
                      items: [orderNumber]
                    }, {
                      columnWidth: .125,
                      layout: 'form',
                      border: false,
                      items: [cBeginDate]
                    }, {
                      columnWidth: .105,
                      layout: 'form',
                      border: false,
                      labelWidth: 30,
                      items: [cEndDate]
                    }, {
                      columnWidth: .31,
                      layout: 'form',
                      border: false,
                      labelWidth: 35,
                      items: [customer]
                    },{
                      columnWidth: .13,
                      layout: 'form',
                      border: false,
                      items: [employeeCBB]
                    }, {
                      columnWidth: .11,
                      layout: 'form',
                      border: false,
                      items: [searchButton]
                    }]
                },{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .12,
                      layout: 'form',
                      border: false,
                      items: [auditingStatus]
                    }, {
                      columnWidth: .125,
                      layout: 'form',
                      border: false,
                      items: [beginDate]
                    }, {
                      columnWidth: .105,
                      layout: 'form',
                      border: false,
                      labelWidth: 30,
                      items: [endDate]
                    }, {
                      columnWidth: .31,
                      layout: 'form',
                      border: false,
                      labelWidth: 35,
                      items: [productCBB]
                    }, {
                      columnWidth: .13,
                      layout: 'form',
                      border: false,
                      items: [department]
                    }, {
                      columnWidth: .11,
                      layout: 'form',
                      border: false,
                      items: [clearButton]
                    }]
                }]
            }]
        });

        //显示销售订单操作时的窗口介面。
        //----------------------------------销售订单Grid-------------------------
        //销售订单Grid Store
        saleOrderDS = new Ext.data.Store({
          paramNames: {
            start: "start",
            limit: "limit"
          },
          baseParams: {
            start: 0,
            limit: pageSize
          },
          proxy: new Ext.data.HttpProxy({
            url: '/sale_order/getAllSaleOrders'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'order_number'
            }, {
              name: 'action_date'
            }, {
              name: 'description'
            }, {
              name: 'auditing_status'
            }, {
              name: 'auditor_name',
              mapping:'auditor',
              convert:function(value,record){
                if(value == ""){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'audit_opinion'
            }, {
              name: 'customer_name',
              mapping:'customer.name'
            },{
              name: 'department_name',
              mapping:'department.name'
            }, {
              name: 'sell_department_name',
              mapping: 'sell_department',
              convert:function(value,record){
                if(value == ""){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'sales_name',
              mapping:'sales',
              convert:function(value,record){
                if(value == "" || value == null){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'employee_name',
              mapping:'employee.name'
            }, {
              name: 'deal_with_status'
            }, {
              name: 'store_status'
            }, {
              name: 'unsafe_discount'
            }, {
              name: 'purchase_status'
            }, {
              name: 'delivery_employee_name',
              mapping: 'delivery_employee',
              convert:function(value,record){
                if(value == ""){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'amount',
              type: 'float'              
            }, {
              name: 'rec_amount',
              type: 'float'
            }, {
              name: 'sale_type',
              convert:function(value,record){
                if(value == "" || value == null){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'sales_strategy',
              convert:function(value,record){
                if(value == "" || value == null){
                  return "";
                }else{
                  return value.name;
                }
              }
            }, {
              name: 'description'
            }, {
              name: 'is_transformed_into_purchase'
            }, {
              name: 'created_at'
            }, {
              name: 'updated_at'
            }])
        });
        
        //生成销售订单Grid的CM
        var saleOrderSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var saleOrderCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),saleOrderSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '销售订单单号',
              dataIndex: 'order_number',
              width: 180
            },{
              header: '客户',
              dataIndex: 'customer_name',
              width: 160
            },{
              header: '总金额',
              dataIndex: 'amount',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 85
            },{
              header: '已收金额',
              dataIndex: 'rec_amount',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 75
            },{
              header: '发货日期',
              dataIndex: 'action_date',
              renderer: Ext.util.Format.dateRenderer('Y-m-d'),
              width: 75
            },{
              header: '销售员',
              dataIndex: 'sales_name',
              width: 60
            },{
              header: '业绩部门',
              dataIndex: 'sell_department_name',
              width: 75
            },{
              header: '操作员',
              dataIndex: 'employee_name',
              width: 55
            },{
              header: '部门',
              dataIndex: 'department_name',
              width: 80
            },{
              header: '授信折扣',
              dataIndex: 'unsafe_discount',
              width: 65,
              renderer: yesOrNoRender
            },{
              header: '审批状态',
              dataIndex: 'auditing_status',
              width: 65,
              renderer: auditingStatusRender
            },{
              header: '审批者',
              dataIndex: 'auditor_name',
              width: 55
            },{
              header: '审批意见',
              dataIndex: 'audit_opinion',
              width: 150
            },{
              header: '处理状态',
              dataIndex: 'deal_with_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '采购状态',
              dataIndex: 'purchase_status',
              width: 70
            },{
              header: '出库状态',
              dataIndex: 'store_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '仓库操作员',
              dataIndex: 'delivery_employee_name',
              width: 70
            },{
              header: '销售类型',
              dataIndex: 'sale_type',
              width: 70
            },{
              header: '销售策略',
              dataIndex: 'sales_strategy',
              width: 80
            },{
              header: '备注',
              dataIndex: 'description',
              width: 230
            },{
              header: '生成日期',
              dataIndex: 'created_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 110
            },{
              header: '修改日期',
              dataIndex: 'updated_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 110
            }
          ]});
        
        //生成要订单的产品的Grid
        var saleOrderGrid = new Ext.grid.GridPanel({
          title:'销售订单列表',
          store: saleOrderDS,
          cm: saleOrderCM,
          sm: saleOrderSM,
          loadMask: true,
          //renderTo: 'order_sale_list_grid',
          width: screenWidth-175,
          height: 345,
          frame: true,
          //title: '进货品种列表',
          //plain:true,
          //plugins: checkColumn,
          bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: saleOrderDS,
            displayInfo: true,
            displayMsg: "显示第 {0} 条到 {1} 条记录，一共 {2} 条",
            emptyMsg: "没有记录"
          }),
          tbar: [{
              text: '新增',
              iconCls: 'addItem',
              handler : function(){
                newSaleOrderWin = new Ext.Window({
                  layout: 'fit',
                  width: 1067,
                  height: 475,
                  closeAction: 'destroy',
                  plain: true,
                  modal: true,
                  constrain:true,
                  //modal: true,
                  title: '新增销售订单',
                  autoLoad: {
                    url: "/sale_order/newSaleOrder",
                    scripts: true
                  }
                });
                newSaleOrderWin.on("destroy",function(){
                  saleOrderDS.reload();
                });
                newSaleOrderWin.resizable = false;
                newSaleOrderWin.show();
              }
            },"-",{
              text: '编辑',
              iconCls: 'editItem',
              handler : function(){
                var records = saleOrderGrid.getSelectionModel().getSelections();
                if(records.length==0){
                  Ext.MessageBox.show({
                    title: '提示信息',
                    msg: "请先选中一条记录后，再编辑。",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                }else{
                  saleOrderId = records[0].get('id');
                  if(records[0].get('auditing_status').indexOf('申请') < 0 && records[0].get('auditing_status')=='' || records[0].get('auditing_status') == '驳回新增'){
                    editSaleOrderWin = new Ext.Window({
                      layout: 'fit',
                      width: 1067,
                      height: 475,
                      closeAction: 'destroy',
                      plain: true,
                      modal: true,
                      constrain:true,
                      //modal: true,
                      title: '编辑销售订单',
                      autoLoad: {
                        url: "/sale_order/editSaleOrder?id="+saleOrderId,
                        scripts: true,
                        callback: function(options, success, response, request)
                        {
                          if (response.responseText === "NoPrivilege"){
                            editSaleOrderWin.close();
                          }
                        }
                      }
                    });
                    editSaleOrderWin.on("destroy",function(){
                      saleOrderDS.reload();
                    });
                    editSaleOrderWin.resizable = false;
                    editSaleOrderWin.show();
                  }else if (records[0].get('auditing_status').indexOf('申请') > -1 || records[0].get('auditing_status') == '通过撤消'){
                    Ext.Msg.alert('提示信息','正在申请、已经撤消的销售订单，不能编辑。');
                  }else if(records[0].get('auditing_status') == '通过新增' || records[0].get('auditing_status') == '通过变更' || records[0].get('auditing_status') == '驳回变更'|| records[0].get('auditing_status') == '驳回撤消'){
                    Ext.MessageBox.confirm('警告',"通过审批的'新增'或'更新'的销售订单在编辑后，要从新通过审批，你确认要编辑此订单吗？",function (button){
                      if(button=='yes'){
                        editSaleOrderAfterAuditWin = new Ext.Window({
                          layout: 'fit',
                          width: 1067,
                          height: 475,
                          closeAction: 'destroy',
                          plain: true,
                          modal: true,
                          constrain:true,
                          //modal: true,
                          title: '审批后，调整销售订单',
                          autoLoad: {
                            url: "/sale_order/editSaleOrderAfterAudit?id="+saleOrderId,
                            scripts: true,
                            callback: function(options, success, response, request)
                            {
                              if (response.responseText === "NoPrivilege"){
                                editSaleOrderAfterAuditWin.close();
                              }
                            }
                          }
                        });
                        editSaleOrderAfterAuditWin.on("destroy",function(){
                          saleOrderDS.reload();
                        });
                        editSaleOrderAfterAuditWin.resizable = false;
                        editSaleOrderAfterAuditWin.show();
                      }
                    });
                  }
                }
              }
            },'-',{
              text: '撤消',
              iconCls: 'cancel',
              handler : function(){
                var records = saleOrderGrid.getSelectionModel().getSelections();
                if (records.length == 0) {
                  return false;
                }else{
                  if(records[0].get('deal_with_status') != '已撤消' && records[0].get('auditing_status').indexOf('申请') < 0 ){
                    var orderNumber = records[0].get('order_number')
                    saleOrderId = records[0].get('id');
                    Ext.MessageBox.confirm("提示","你确认要申请撤消订单号为： \""+orderNumber+"\" 的销售订单吗？",function(btn){
                      if(btn=="yes"){
                        Ext.Ajax.request({
                          url : '/sale_order/applyToCancel?id=' + saleOrderId,
                          success : function (result, request) {
                            saleOrderDS.reload();
                          },
                          failure : function (result, request){
                            Ext.MessageBox.show({
                              title: '消息',
                              msg: "通讯失败，请从新操作",
                              buttons: Ext.MessageBox.OK,
                              icon: Ext.MessageBox.WARNING
                            });
                          },
                          method : 'GET'
                        });
                      }else{
                        //alert("no");
                      }
                    });
                  }else{
                    Ext.Msg.alert('提示信息','已经撤消或正于申请状态的各类订单，不能撤消。');
                  }
                }
              }
            },'-',{
              text: '打印销售凭据',
              iconCls: 'print',
              handler : function(){
                var records = saleOrderGrid.getSelectionModel().getSelections();
                if (records.length == 0) {
                  return false;
                }else{
                  if(records[0].get('deal_with_status') != '已撤消'){
                    this.disable();
                    saleOrderId = records[0].get('id');
                    //LODOP.SET_PRINT_PAGESIZE(1,0,0,'A5')
                    LODOP.PRINT_INIT("");
                    LODOP.SET_PRINT_PAGESIZE(1,"210mm","148mm","");
                    //LODOP.SET_PRINT_PAGESIZE(1,"210mm","297mm","");
                    //LODOP.SET_PRINT_PAGESIZE(1,"148mm","210mm","")
                    
                    LODOP.ADD_PRINT_URL(30,'5%',"90%","100%",'http://'+window.location.host+'/sale_order/sale_order_print_header?id='+saleOrderId);
                    LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
                    LODOP.ADD_PRINT_TBURL(150,'5%',"90%","43%",'http://'+window.location.host+'/sale_order/sale_order_print_content?id='+saleOrderId);
                    LODOP.SET_PRINT_STYLEA(0,"ItemType",4);
                    LODOP.ADD_PRINT_URL(415,'5%',"90%","100%",'http://'+window.location.host+'/sale_order/sale_order_print_footer?id='+saleOrderId);
                    LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
                    LODOP.ADD_PRINT_TEXT(490,'15%',"80%","8%","第一联：成本（白） 第二联：财务（绿） 第三联：提货（粉） 第四联：客户（黄） 第五联：销售（兰）");
                    LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
                    LODOP.ADD_PRINT_TEXT(510,'35%',"90%","8%","页号：第#页/共&页 打印日期："+getDate());
                    LODOP.SET_PRINT_STYLEA(0,"ItemType",2);
                    
                    LODOP.PREVIEW();
                    this.enable();
                    //window.open('/test/sale_order_print?id='+saleOrderId,'_blank','width=0,height=0,toolbar=no,menubar=no,location=no');
                  }
                }
              }
            }]
        });
        saleOrderDS.load();
        
        saleOrderGrid.on('rowdblclick', function(gridPanel, rowIndex, e){
          saleOrderId = saleOrderDS.getAt(rowIndex).get('id');
          var saleOrderNumber = saleOrderDS.getAt(rowIndex).get('order_number');
          //saleOrderDS.reload();
          saleOrderDetailDS.removeAll();
          saleOrderDetailDS.baseParams.sale_order_id = saleOrderId;
          saleOrderDetailDS.load();
          saleOrderDetailGrid.setTitle("销售订单："+saleOrderNumber+"，的详细信息");
        });

        saleOrderGrid.on('rowcontextmenu', function(grid, rowIndex, e){
          //初始化所有右键菜单为不可用
          deliveryForSaleItem.setDisabled(true);
          //recItem.setDisabled(true);
          intoPurchaseItem.setDisabled(true);
          returnedItem.setDisabled(true);
          finishPurchaseStatusItem.setDisabled(true);
          cancelPurchaseStatusItem.setDisabled(true);
          
          saleOrderId = saleOrderDS.getAt(rowIndex).get('id');
          currentOrderNumber = saleOrderDS.getAt(rowIndex).get('order_number');
          var auditingStatus = saleOrderDS.getAt(rowIndex).get('auditing_status');
          var purchaseStatus = saleOrderDS.getAt(rowIndex).get('purchase_status');
          var intoPurchase = saleOrderDS.getAt(rowIndex).get('is_transformed_into_purchase');
          if (auditingStatus.indexOf("通过") > -1){
            deliveryForSaleItem.setDisabled(false);
            recItem.setDisabled(false);
          }else {
            deliveryForSaleItem.setDisabled(true);
          }
          
          if (intoPurchase=="否" && auditingStatus.indexOf("通过") > -1){
            intoPurchaseItem.setDisabled(false);
          }else {
            intoPurchaseItem.setDisabled(true);
          }

          //只要通过审批就可以退货，不一定非要转为采购订单以后，有时候库里有货，有销售订单，直接就可以销售。
          if (auditingStatus.indexOf("通过") > -1){
            returnedItem.setDisabled(false);
          }else{
            returnedItem.setDisabled(true);
          }

          if (purchaseStatus == ""){
            finishPurchaseStatusItem.setDisabled(false);          
          }else{
            cancelPurchaseStatusItem.setDisabled(false);
          }
          
          e.preventDefault();
          rightClick.showAt(e.getXY());
        });
        
        //############ 订单-右键菜单 ##########
        var deliveryForSaleItem = new Ext.menu.Item({
          text: '【相关出库单信息】',
          //iconCls: 'album',
          handler: rightMenuDeliveryForSaleFn
        });

        function rightMenuDeliveryForSaleFn(){
          deliveryForSaleWin = new Ext.Window({
            layout: 'fit',
            width:1098,
            height: 600,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '销售订单\"'+currentOrderNumber+'\"相关的出库单信息',
            autoLoad: {
              url: "/sale_order/deliveryForSaleList?id="+saleOrderId,
              scripts: true
            }
          });
          deliveryForSaleWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          deliveryForSaleWin.resizable = false;
          deliveryForSaleWin.show();
        }

        var returnedForSaleItem = new Ext.menu.Item({
          text: '【相关退货订单信息】',
          //iconCls: 'album',
          handler: rightMenuReturnedForSaleFn
        });

        function rightMenuReturnedForSaleFn(){
          returnedForSaleWin = new Ext.Window({
            layout: 'fit',
            width:998,
            height: 600,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '销售订单\"'+currentOrderNumber+'\"相关的退货订单信息',
            autoLoad: {
              url: "/sale_order/returnedForSaleList?id="+saleOrderId,
              scripts: true
            }
          });
          returnedForSaleWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          returnedForSaleWin.resizable = false;
          returnedForSaleWin.show();
        }
        
        var intoPurchaseItem = new Ext.menu.Item({
          text: '【转为采购订单】',
          //iconCls: 'album',
          handler: rightMenuIntoPurchaseFn
        });

        function rightMenuIntoPurchaseFn(){
          saleIntoPurchaseWin = new Ext.Window({
            layout: 'fit',
            width: 860,
            height: 495,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '转换销售订单：\"'+currentOrderNumber+'\"为采购订单',
            autoLoad: {
              url: "/purchase_order/newPurchaseFromSale?id="+saleOrderId,
              scripts: true
            }
          });
          saleIntoPurchaseWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          saleIntoPurchaseWin.resizable = false;
          saleIntoPurchaseWin.show();
        }

        var recItem = new Ext.menu.Item({
          text: '【收款记录】',
          //iconCls: 'album',
          handler: rightMenuRecFn
        });

        function rightMenuRecFn(){
          recListWin = new Ext.Window({
            layout: 'fit',
            width: 1000,
            height: 275,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '销售订单：\"'+currentOrderNumber+'\"的收款记录',
            autoLoad: {
              url: "/receivables/receivablesListForSale?id="+saleOrderId,
              scripts: true
            }
          });
          recListWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          recListWin.resizable = false;
          recListWin.show();
        }

        var returnedItem = new Ext.menu.Item({
          text: '【销售退货】',
          //iconCls: 'album',
          handler: rightMenuReturnedFn
        });

        function rightMenuReturnedFn(){
          newSaleReturnedWin = new Ext.Window({
            layout: 'fit',
            width: 1000,
            height: 500,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '销售订单：\"'+currentOrderNumber+'\"的退货记录',
            autoLoad: {
              url: "/sale_returned/newSaleReturned?id="+saleOrderId,
              scripts: true
            }
          });
          newSaleReturnedWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          newSaleReturnedWin.resizable = false;
          newSaleReturnedWin.show();
        }

        var exchangeItem = new Ext.menu.Item({
          text: '【销售换货】',
          //iconCls: 'album',
          handler: rightMenuExchangeFn
        });

        function rightMenuExchangeFn(){
          newSaleExchangeWin = new Ext.Window({
            layout: 'fit',
            width: 1000,
            height: 500,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '销售订单：\"'+currentOrderNumber+'\"的换货记录',
            autoLoad: {
              url: "/sale_exchange/newSaleExchange?id="+saleOrderId,
              scripts: true
            }
          });
          newSaleExchangeWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          newSaleExchangeWin.resizable = false;
          newSaleExchangeWin.show();
        }
        
        var saleOrderHxItem = new Ext.menu.Item({
          text: '【变更历史】',
          //iconCls: 'album',
          handler: rightMenusaleOrderHxFn
        });

        function rightMenusaleOrderHxFn(){
          saleOrderHxWin = new Ext.Window({
            layout: 'fit',
            width: 960,
            height: 550,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '销售订单：\"'+currentOrderNumber+'\"的变更记录',
            autoLoad: {
              url: "/sale_order/hxListForSale?id="+saleOrderId,
              scripts: true
            }
          });
          saleOrderHxWin.on("destroy",function(){
            saleOrderDS.reload();
          });
          saleOrderHxWin.resizable = false;
          saleOrderHxWin.show();
        }

        var finishPurchaseStatusItem = new Ext.menu.Item({
          text: '【设置采购完毕状态】',
          //iconCls: 'album',
          handler: rightMenuFinishPurchaseStatusFn
        });

        function rightMenuFinishPurchaseStatusFn(){
          Ext.Ajax.request({
            url : '/sale_order/setupPurchaseStatus',
            success : function (result, request) {
              saleOrderDS.reload();
            },
            failure : function (result, request){
              Ext.MessageBox.show({
                title: '消息',
                msg: "通讯失败，请从新操作",
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.WARNING
              });
            },
            method : 'GET',
            params : {
              id : saleOrderId,
              purchase_status : 'finish'
            }
          });
        }

        var cancelPurchaseStatusItem = new Ext.menu.Item({
          text: '【取消采购完毕状态】',
          //iconCls: 'album',
          handler: rightMenuCancelPurchaseStatusFn
        });

        function rightMenuCancelPurchaseStatusFn(){
          Ext.Ajax.request({
            url : '/sale_order/setupPurchaseStatus',
            success : function (result, request) {
              saleOrderDS.reload();
            },
            failure : function (result, request){
              Ext.MessageBox.show({
                title: '消息',
                msg: "通讯失败，请从新操作",
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.WARNING
              });
            },
            method : 'GET',
            params : {
              id : saleOrderId
            }
          });
        }
        
        var rightClick = new Ext.menu.Menu({
          items: [deliveryForSaleItem,'-',returnedForSaleItem,'-',recItem,'-',returnedItem,'-',saleOrderHxItem,'-',finishPurchaseStatusItem,cancelPurchaseStatusItem]
        });

        //--------------------------销售订单详细，双击后可显示数据----------------
        //销售订单Grid Store Detail
        var saleOrderDetailDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/sale_order/getSaleOrderDetailsBalanceById'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'product_name'
            },{
              name: 'product_number'
            },{
              name: 'spec'
            },{
              name: 'quantity',
              type: 'int'
            }, {
              name: 'unit_price',
              type: 'float'
            }, {
              name: 'discount',
              type: 'float'
            }, {
              name: 'amount',
              type: 'float'
            }, {
              name: 'balance_quantity',
              type: 'int'
            }, {
              name: 'is_suit',
              mapping:'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }, {
              name: 'description'
            }])
        });

        //生成销售订单详细表的Grid的CM
        var saleOrderDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var saleOrderDetailCM = new Ext.grid.ColumnModel(
        {defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),saleOrderDetailSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 60
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 270
            },{
              header: '编号',
              dataIndex: 'product_number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 70
            },{
              header: '数量',
              dataIndex: 'quantity',
              align: 'right',
              width: 60
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: moneyPrivilegeRender,
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 70
            },{
              header: '折扣',
              dataIndex: 'discount',
              renderer: moneyPrivilegeRender,
              renderer: Ext.util.Format.numberRenderer('0,000.000000'),
              width: 70
            },{
              header: '总价',
              dataIndex: 'amount',
              align: 'right',
              renderer: moneyPrivilegeRender,
              width: 80
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '出库差比',
              dataIndex: 'balance_quantity',
              align: 'right',
              width: 80
            },{
              header: '备注',
              dataIndex: 'description',
              width: 170
            }
          ]});
        
        //生成要订单的产品的Grid
        var saleOrderDetailGrid = new Ext.grid.GridPanel({
          title:'订单详细列表',
          store: saleOrderDetailDS,
          cm: saleOrderDetailCM,
          sm: saleOrderDetailSM,
          loadMask: true,
          width: screenWidth-175,
          height: 275,
          frame: true
          //title: '进货品种列表',
          //plain:true,
          //plugins: checkColumn,
        });

        //总的panel
        var workbenchPanel = new Ext.Panel({
          width: screenWidth-175,
          height: 735,
          //html: '&lt;empty panel&gt;',
          //cls:'cellpadding:10',
          /*layout: {
            type:'vbox',
            align:'stretch'
          },*/
          frame:false,
          layout:'table',
          layoutConfig: {columns:1},
          defaults:{margins:'5 5 5 5'},
          //bodyStyle: 'padding:15px;align:center',
          //listeners: {
          //expand: showAgileDiagram
          //},
          items:[queryFormPanel,saleOrderGrid,saleOrderDetailGrid]
        });
        workbenchPanel.render("order_sale_list_workbench");

      })
    </script>
  </head>
  <body>
    <div id="order_sale_list_workbench"></div>    
  </body>
</html>